<?php

namespace App\Logic;

use Common\Logic\BaseLogic;

class JoinLogic extends BaseLogic
{
    private $joinModel;
    private $listModel;
    private $userModel;
    public static $field = '';

    public function __construct()
    {
        parent::__construct();
        $this->joinModel = D('Join');
        $this->listModel = D('List');
        $this->userModel = D('User');
    }

    /**
     * 根据条件统计
     *
     * @param array $where
     *
     * @return mixed
     */
    public function statistics($where = array())
    {
        return $this->joinModel->where($where)->count();
    }

    /**
     * 获取单条join.
     *
     * @param $where
     *
     * @return mixed
     */
    public function findJoinInfo($where)
    {
        $info = $this->joinModel->where($where)->find();

        return static::$res->suc('成功', $info);
    }

    /**
     * 获取参与列表.
     *
     * @param int   $page
     * @param int   $size
     * @param array $where
     *
     * @return mixed
     */
    public function getJoinList($page = 1, $size = 20, $where = array())
    {
        $list = $this->joinModel->where($where)->page($page.','.$size)->order('id desc')->select();
        $count = $this->statistics($where);

        return static::$res->suc('成功', array(
            'list' => $list,
            'count' => $count,
        ));
    }

    /**
     * 获取参加任务的user列表.
     *
     * @param int   $page
     * @param int   $size
     * @param array $where
     *
     * @return mixed
     */
    public function getJoinUserList($page = 1, $size = 20, $where = array())
    {
        $userTableName = $this->userModel->getTableName();
        $joinTableName = $this->joinModel->getTableName();
        $list = $this->joinModel->join('left join '.$userTableName.' on '.$userTableName.'.id='.$joinTableName.'.user_id')
            ->where($where)->page($page.','.$size)->order($joinTableName.'.id desc')->group('user_id')
            ->select();
        $count = $this->statistics($where);

        return static::$res->suc('成功', array(
            'list' => $list,
            'count' => $count,
        ));
    }

    /**
     * 获取参加的task列表.
     *
     * @param int   $page
     * @param int   $size
     * @param array $where
     *
     * @return mixed
     */
    public function getJoinTaskList($page = 1, $size = 20, $where = array())
    {
        $taskTableName = $this->listModel->getTableName();
        $joinTableName = $this->joinModel->getTableName();

        $list = $this->joinModel->where($where)->page($page.','.$size)->order('id desc')->select();
        foreach ($list as &$vo) {
            if ($vo['task_id'] < 0) {
                continue;
            }

            $taskWhere = array(
                'id' => $vo['task_id'],
            );
            $taskInfo = $this->listModel->where($taskWhere)->find();
            $vo['cover'] = $taskInfo['cover'];
        }

        $count = $this->statistics($where);

        return static::$res->suc('成功', array(
            'list' => $list,
            'count' => $count,
        ));
    }

    /**
     * 加入任务
     *
     * @param $taskId
     * @param $userId
     *
     * @return mixed
     */
    public function join($taskId, $userId)
    {
        if (empty($taskId)) {
            return static::$res->err('请传入任务ID');
        }
        if (empty($userId)) {
            return static::$res->err('用户ID不能为空');
        }

        $taskLogic = A('App/Task', 'Logic');
        $taskInfoRes = $taskLogic->getDetial($taskId);
        if (!static::$res->isSuc($taskInfoRes)) {
            return $taskInfoRes;
        }
        $taskInfo = $taskInfoRes['Result'];
        $beginTime = strtotime($taskInfo['begin_time']);
        $endTime = strtotime($taskInfo['end_time']);
        $nowTime = time();

        if ($taskInfo['num'] <= $taskInfo['join_num']) {
            return static::$res->err('任务已经被抢完');
        }

        if ($beginTime >= $nowTime) {
            return static::$res->err('任务未开始');
        }
        if ($endTime <= $nowTime) {
            return static::$res->err('任务已结束');
        }

        $joinWhere = array(
            'user_id' => $userId,
            'state' => 1,
            'task_type' => $taskInfo['type'],
        );
        if ($this->statistics($joinWhere) >= C('MAX_JOIN_TASK_COUNT')) {
            return static::$res->err('超过最大加入数量');
        }

        $joinWhere['task_id'] = $taskId;
        $joinWhere['state'] = array('neq', -1);
        if ($this->statistics($joinWhere)) {
            return static::$res->err('你已经加入过本任务');
        }

        $data = array(
            'user_id' => $userId,
            'task_id' => $taskId,
            'task_title' => $taskInfo['title'],
            'task_type' => $taskInfo['type'],
            'income' => $taskInfo['income'],
            'admin_user_id' => $taskInfo['user_id'],
            'state' => 1,
            'join_time' => date('Y-m-d H:i:s'),
        );
        $id = $this->joinModel->add($data);
        if (empty($id)) {
            return static::$res->err('数据库异常，加入失败');
        }

        $taskWhere = array(
            'id' => $taskId,
        );

        $this->listModel->where($taskWhere)->setInc('join_num');

        return static::$res->suc('参加成功', $id);
    }

    /**
     * 取消任务
     *
     * @param array $where
     *
     * @return mixed
     */
    public function cancelJoinTask($where = array())
    {
        $joinInfoRes = $this->findJoinInfo($where);
        $taskId = $joinInfoRes['Result']['task_id'];
        if (empty($taskId)) {
            return static::$res->err('未找到加入记录');
        }

        $count = $this->joinModel->where($where)->save(array('state' => -1));

        if (empty($count)) {
            return static::$res->err('数据库异常没有任何改变');
        }

        if ($taskId) {
            //已抢数量-1
            $this->listModel->where(array(
                'id' => $taskId,
            ))->setDec('join_num');
        }

        return static::$res->suc('取消成功', $count);
    }

    /**
     * 完成任务
     *
     * @param $taskId
     * @param $userId
     * @param $phone
     * @param $doingTime
     * @param $proof
     *
     * @return mixed
     */
    public function finishJoinTask($taskId, $userId, $phone, $doingTime, $proof, $joinId = '')
    {
        if (empty($taskId)) {
            return static::$res->err('请传入任务ID');
        }
        if (empty($userId)) {
            return static::$res->err('用户ID不能为空');
        }

        if (empty($phone)) {
            return static::$res->err('手机号不能为空');
        }

        if (!validate($phone, 'mobile')) {
            return static::$res->err('手机格式错误');
        }

        if (empty($doingTime)) {
            return static::$res->err('任务完成时间不能为空');
        }

        if (is_array($proof)) {
            $proof = implode(',', $proof);
        }

        if (empty($proof)) {
            return static::$res->err('完成凭证不能为空');
        }

        $joinWhere = array(
            'user_id' => $userId,
            'task_id' => $taskId,
            'state' => array('neq', -1),
        );

        $joinInfo = $this->joinModel->where($joinWhere)->find();
        if (empty($joinInfo)) {
            return static::$res->err('你未加入本任务');
        }

        if (1 != $joinInfo['state'] && -2 != $joinInfo['state']) {
            return static::$res->err('领取的任务已失效');
        }

        $data = array(
            'state' => 2,
            'finish_time' => date('Y-m-d H:i:s'),
            'phone' => $phone,
            'doing_time' => date('Y-m-d H:i:s', strtotime($doingTime)),
            'proof' => $proof,
        );

        $saveWhere = array(
            'id' => $joinInfo['id'],
        );

        $count = $this->joinModel->where($saveWhere)->save($data);
        if (empty($count)) {
            return static::$res->err('数据库异常,没有任何改变');
        }

        $this->listModel->where(array(
            'id' => $taskId,
        ))->setInc('finish_num');

        return static::$res->suc('操作成功', $count);
    }

    /**
     * 加入问卷任务,并发放奖金.
     *
     * @param [type] $data
     *
     * @return void
     */
    public function joinGmoTask($data)
    {
        $userId = $data['member_id'];
        if (empty($userId)) {
            return static::$res->err('用户ID不能为空');
        }

        $userInfo = $this->userModel->where(array(
            'id' => $userId,
            'user_state' => 1,
        ))->find();

        if (empty($userInfo)) {
            return static::$res->err('未找到用户');
        }

        if (0 >= $data['point']) {
            return static::$res->err('问卷未完成');
        }

        //写死每个问题4元
        $income = 400;
        //价格小鱼400分的就按原价给
        if ($data['point'] <= 400) {
            $income = $data['point'];
        }

        $data = array(
            'user_id' => $userId,
            'task_id' => -1,
            'task_title' => $data['survey_name'],
            'task_type' => 10,
            'income' => $income,
            'admin_user_id' => 1000000,
            'state' => 3,
            'join_time' => date('Y-m-d H:i:s'),
            'finish_time' => date('Y-m-d H:i:s'),
            'audit_user_id' => 1000000,
            'audit_time' => date('Y-m-d H:i:s'),
            'phone' => $userInfo['phone'],
            'doing_time' => date('Y-m-d H:i:s'),
            'other_id' => $data['survey_id'],
            'other_info' => $data['grant_times'],
        );

        $id = $this->joinModel->add($data);
        if (empty($id)) {
            return static::$res->err('数据库异常,保存失败');
        }

        $incomeLogic = A('Console/Income', 'Logic');
        $incomeRes = $incomeLogic->addTaskIncome($id);
        if (static::$res->isErr($incomeRes)) {
            //删除添加的数据
            $this->joinModel->where(array(
                'id' => $id,
            ))->delete();

            return $incomeRes;
        }

        return static::$res->suc('成功');
    }

	/**
     * 加入聚享游任务,并发放奖金.
     *
     * @param [type] $data
     *
     * @return void
     */
    public function joinGatheringTourTask($data)
    {
        $userId = $data['resource_id'];
        if (empty($userId)) {
            return static::$res->err('用户ID不能为空');
        }

        $userInfo = $this->userModel->where(array(
            'id' => $userId,
            'user_state' => 1,
        ))->find();

        if (empty($userInfo)) {
            return static::$res->err('未找到用户');
        }

        if (empty($data['prize_id'])) {
            return static::$res->err('无效奖励流水');
        }

        //奖励
        $income = $data['task_prize']*100;
        $info=$this->joinModel->where(array(
            'task_type' => 11,
            'other_id' => $data['prize_id'],
        ))->find();
        //查询是否重复的奖励流水
        if(!empty($info)){
            return static::$res->err('重复奖励流水');
        }
        $data = array(
            'user_id' => $userId,
            'task_id' => -1,
            'task_title' => $data['title'],
            'task_type' => 11,
            'income' => $income,
            'admin_user_id' => 1000000,
            'state' => 3,
            'join_time' => date('Y-m-d H:i:s'),
            'finish_time' => date('Y-m-d H:i:s'),
            'audit_user_id' => 1000000,
            'audit_time' => date('Y-m-d H:i:s'),
            'phone' => $userInfo['phone'],
            'doing_time' => date('Y-m-d H:i:s'),
            'other_id' => $data['prize_id'],
            'other_info' => $data['type'],
        );

        $id = $this->joinModel->add($data);
        if (empty($id)) {
            return static::$res->err('数据库异常,保存失败');
        }

        $incomeLogic = A('Console/Income', 'Logic');
        $incomeRes = $incomeLogic->addTaskIncome($id);
        if (static::$res->isErr($incomeRes)) {
            //删除添加的数据
            $this->joinModel->where(array(
                'id' => $id,
            ))->delete();

            return $incomeRes;
        }

        return static::$res->suc('成功');
    }
}
